package com.nd.controller.admin;

import cn.hutool.core.date.DateTime;
import com.nd.dao.JurisdictionMapper;
import com.nd.dao.LogMapper;
import com.nd.pojo.bean.*;
import com.nd.pojo.bo.LoginAdminBo;
import com.nd.pojo.bo.StorageBO;
import com.nd.pojo.vo.BaseRespVo;
import com.nd.pojo.vo.DashboardVo;
import com.nd.pojo.vo.ErrorAndErrno;
import com.nd.pojo.vo.LoginAdminVo;
import com.nd.realm.MallToken;
import com.nd.service.AdminService;
import com.nd.service.StorageService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    AdminService adminService;
    @Autowired
    StorageService storageService;
    @Autowired
    LogMapper logMapper;
    @Autowired
    JurisdictionMapper jurisdictionMapper;



    @RequestMapping("auth/login")
    public BaseRespVo login(@RequestBody LoginAdminBo admin) {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new MallToken(admin.getUsername(),admin.getPassword(),"admin"));
        }catch (AuthenticationException|NullPointerException e){
            BaseRespVo fail = BaseRespVo.fail("账户或密码错误！");
            logWriter(fail,"匿名用户",null,0,"登录失败，账户或密码错误",false);
            return fail;
//        }catch (IncorrectCredentialsException e){
//            BaseRespVo fail = BaseRespVo.fail("密码错误！");
//            logWriter(fail,admin.getUsername(),null,0,"登录");
//            return fail;
        }catch (Exception e){
//            org.apache.shiro.authc.AuthenticationException
            BaseRespVo fail = BaseRespVo.fail("登录异常");
            logWriter(fail,admin.getUsername(),null,0,"登录失败，登录异常",false);
            return fail;
        }
        Admin principal = (Admin) subject.getPrincipal();
        Date lastLoginTime = principal.getLastLoginTime();
        String id = (String) subject.getSession().getId();
        logWriter(BaseRespVo.ok(id),admin.getUsername(),lastLoginTime,1,"登录",true);
        return BaseRespVo.ok(id);
    }

    @RequestMapping("auth/logout")
    public BaseRespVo logout(){
        Subject subject = SecurityUtils.getSubject();
        if(subject != null) {
            Admin principal = (Admin) subject.getPrincipal();
            Date lastLoginTime = principal.getLastLoginTime();
            String username = principal.getUsername();
            logWriter(BaseRespVo.ok(), username, lastLoginTime, 1, "登出",true);
            subject.logout();
        }
        return BaseRespVo.ok();

    }

    @RequestMapping("auth/info")
    public BaseRespVo info() {
        LoginAdminVo loginAdminVo = adminService.getLoginAdminVo();
        return BaseRespVo.ok(loginAdminVo);
    }

    @RequestMapping("dashboard")
    //后台首页
    public BaseRespVo dashboard(){
        DashboardVo dashboardVo = adminService.queryDashboardVo();
        return BaseRespVo.ok(dashboardVo);
    }

    @RequestMapping("storage/create")
    public BaseRespVo upload(@RequestParam("file") MultipartFile myFile) throws Exception {
        Storage uploads = storageService.uploadFiles(myFile);
        if(uploads == null) return BaseRespVo.fail();
        return BaseRespVo.ok(uploads);
    }
    @PostMapping("storage/update")
    public ErrorAndErrno updateStorage(@RequestBody StorageBO bo) throws Exception {

        ErrorAndErrno errorAndErrno = storageService.updateStorage(bo.getId(), bo.getName());

        return errorAndErrno;
    }
    @PostMapping("storage/delete")
    public ErrorAndErrno deleteStorage(@RequestBody StorageBO bo) throws Exception {

        ErrorAndErrno errorAndErrno = storageService.updateStorage(bo.getId(),null);

        return errorAndErrno;
    }

    private void logWriter(BaseRespVo result, String username, Date lastLoginTime, Integer type, String work,boolean status){

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest();
        String ip = request.getRemoteAddr();//地址
        String requestURI = request.getRequestURI();
        DateTime now = DateTime.now();//添加修改时间
        String errmsg = "";//result
        try {
            errmsg =result.getErrmsg();//result
        } catch (Exception e) {
            e.printStackTrace();
        }

        if ("成功".equals(errmsg)){ status=true; }else { status=false;}


        JurisdictionExample example = new JurisdictionExample();
        example.createCriteria().andApiLike("%"+requestURI+"%");

        List<Jurisdiction> jurisdictions = jurisdictionMapper.selectByExample(example);
        String action="";
        for (Jurisdiction jurisdiction : jurisdictions) {
            String pid = jurisdiction.getPid();
            String label= jurisdiction.getLabel();
            action += pid+label+"\n";
        }
        if ("".equals(action))action=requestURI;

        Log build = Log.builder().action(work).addTime(now).updateTime(now).admin(username)
                .ip(ip).type(type).status(status).result(status?"成功":"失败").comment("").deleted(false).build();
        logMapper.insert(build);
    }


}
